class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        int row = mat.size();
        int col = mat[0].size();
        vector<vector<int>> vis(row, vector<int>(col, -1));
        int dx[4] = { 0, 0, 1, -1 };
        int dy[4] = { 1, -1, 0, 0 };
        queue<pair<int, int>> q;
        for (int i = 0; i < row; i++)
            for (int j = 0; j < col; j++)
                if (mat[i][j] == 0)
                {
                    vis[i][j] = 0;
                    q.push({ i, j });
                }
        while (!q.empty())
        {
            auto [x, y] = q.front();
            q.pop();
            for (int k = 0; k < 4; k++)
            {
                int i = x + dx[k];
                int j = y + dy[k];
                if (i >= 0 && i < row && j >= 0 && j < col && vis[i][j] == -1)
                {
                    vis[i][j] = vis[x][y] + 1;
                    q.push({ i, j });
                }
            }
        }
        return vis;
    }



};
class Solution {
public:

    int numEnclaves(vector<vector<int>>& mat) {
        int row = mat.size();
        int col = mat[0].size();
        vector<vector<int>> vis(row, vector<int>(col, -1));
        int dx[4] = { 0, 0, 1, -1 };
        int dy[4] = { 1, -1, 0, 0 };
        queue<pair<int, int>> q;
        for (int i = 0; i < row; i++)
            for (int j = 0; j < col; j++)
                if (!(i != 0 && i != row - 1 && j != 0 && j != col - 1) && mat[i][j] == 1)
                {
                    vis[i][j] = 2;
                    q.push({ i, j });
                }
        while (!q.empty())
        {
            auto [x, y] = q.front();
            q.pop();
            for (int k = 0; k < 4; k++)
            {
                int i = x + dx[k];
                int j = y + dy[k];
                if (i >= 0 && i < row && j >= 0 && j < col && mat[i][j] == 1 && vis[i][j] == -1)
                {
                    vis[i][j] = 2;
                    q.push({ i, j });
                }
            }
        }
        int ret = 0;
        for (int i = 0; i < row; i++)
            for (int j = 0; j < col; j++)
                if (vis[i][j] == -1 && mat[i][j] == 1)
                    ret++;
        return ret;
    }
};